package URL网络编程;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class URL网络编程实现Tomcat服务端数据下载 {
    public static void main(String[] args) {
        HttpURLConnection urlConnection= null;
        InputStream is = null;
        FileOutputStream fos = null;

        try {
            //1.创建URL对象
            URL url = new URL("http://127.0.0.1:8080/SSM_CRUD_war/work/164.jpeg");
            //2.获取关于服务器的链接
            /**
             *  urlConnection = (HttpURLConnection) url.openConnection();
             * 由于本地电脑没有配置Tomcat服务器，暂时不能演示，待解决！！！
             */
            urlConnection = (HttpURLConnection) url.openConnection();
            //3.获取对象链接，现在才可以真正的访问服务器
            urlConnection.connect();
            //4.获取一个输入流读取数据
            is = urlConnection.getInputStream();
            //5.获取一个输出流下载数据
            fos = new FileOutputStream("网络编程\\16.mp4");

            byte[] buffer = new byte[1024];
            int len;
            while((len = is.read(buffer)) != -1){
                fos.write(buffer,0,len);
            }

            System.out.println("下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5.资源关闭
            if (fos != null) {

                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }if (is != null) {

                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }if (urlConnection != null) {

                urlConnection.disconnect();
            }
        }




    }
}
